<template>
  <div>
    <el-form ref="addFormRef" :rules="rules" :model="addForm.data" label-width="120">
      <el-row>
        <el-form-item label="物业名称" prop="comId">
          <el-select
            v-model="addForm.data.comId"
            filterable
            style="width: 320px"
            placeholder="请选择物业名称"
          >
            <el-option
              v-for="item in comNameList.data"
              :key="item.key"
              :label="item.value"
              :value="item.key"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="场库名称" prop="name">
          <el-input
            v-model="addForm.data.name"
            style="width: 320px"
            placeholder="请输入场库名称"
          />
        </el-form-item>
      </el-row>
      <el-row>
        <el-form-item label="运营状态" prop="status">
          <el-select
            v-model="addForm.data.status"
            filterable
            style="width: 320px"
            placeholder="请选择运营状态"
          >
            <el-option
              v-for="item in statusList.data"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="车场类别" prop="category">
          <el-select
            v-model="addForm.data.category"
            filterable
            style="width: 320px"
            placeholder="请选择车场类别"
          >
            <el-option
              v-for="item in categoryList.data"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-row>
      <el-row>
        <el-form-item label="建筑类别" prop="type">
          <el-select
            v-model="addForm.data.type"
            filterable
            style="width: 320px"
            placeholder="请选择建筑类别"
          >
            <el-option
              v-for="item in typeList.data"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="是否含套场" prop="infield">
          <el-select
            v-model="addForm.data.infield"
            filterable
            style="width: 320px"
            placeholder="请选择套场"
          >
            <el-option
              v-for="item in infieldList.data"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-row>
      <el-row>
        <el-form-item label="外场泊位数" prop="totalSpaces" v-if="addForm.data.infield == 1">
          <el-input
            v-model="addForm.data.totalSpaces"
            style="width: 320px"
            placeholder="请输入外场泊位数"
          />
        </el-form-item>
        <el-form-item label="总泊位数" prop="totalSpaces" v-if="addForm.data.infield == 0">
          <el-input
            v-model="addForm.data.totalSpaces"
            style="width: 320px"
            placeholder="请输入总泊位数"
          />
        </el-form-item>
        <el-form-item label="套场泊位数" prop="inSpaces" v-if="addForm.data.infield == 1">
          <el-input
            v-model="addForm.data.inSpaces"
            style="width: 320px"
            placeholder="请输入套场泊位数"
          />
        </el-form-item>
        <el-form-item label="套场泊位数" v-if="addForm.data.infield == 0">
          <el-input style="width: 320px" disabled />
        </el-form-item>
      </el-row>
      <el-row>
        <el-form-item label="经度" prop="longitude">
          <el-input
            v-model="addForm.data.longitude"
            style="width: 320px"
            placeholder="请输入经度"
          />
        </el-form-item>
        <el-form-item label="纬度" prop="latitude">
          <el-input
            v-model="addForm.data.latitude"
            style="width: 320px"
            placeholder="请输入纬度"
          />
        </el-form-item>
      </el-row>
      <el-row>
        <el-form-item label="具体位置" prop="address">
          <el-input
            v-model="addForm.data.address"
            style="width: 760px"
            placeholder="请输入具体位置"
          />
        </el-form-item>
      </el-row>
      <el-row>
        <el-form-item label="联系人" prop="link">
          <el-input
            v-model="addForm.data.link"
            style="width: 320px"
            placeholder="请输入联系人"
          />
        </el-form-item>
        <el-form-item label="联系电话" prop="phone">
          <el-input
            v-model="addForm.data.phone"
            style="width: 320px"
            placeholder="请输入联系电话"
          />
        </el-form-item>
      </el-row>
      <el-row>
        <el-form-item label="车场图片" prop="fileId">
          <el-upload
            action="#"
            v-model:file-list="fileList"
            :before-upload="beforeAvatarUpload"
            :on-change="fileListUpLoad"
            :limit="3"
            :disabled="fileList.length >= 3 ? true : false"
            list-type="picture-card"
          >
            <el-icon><Plus /></el-icon>
            <template #file="{ file }">
              <div>
                <img class="el-upload-list__item-thumbnail" :src="file.url" alt="" />
                <span class="el-upload-list__item-actions">
                  <!-- <span
                    class="el-upload-list__item-preview"
                    @click="handlePictureCardPreview()"
                  >
                    <el-icon><ZoomIn /></el-icon>
                  </span> -->

                  <span class="el-upload-list__item-delete" @click="handleRemove(file)">
                    <el-icon><Delete /></el-icon>
                  </span>
                </span>
              </div>
            </template>
          </el-upload>
        </el-form-item>
      </el-row>
      <el-row>
        <el-col :span="11">
          <el-form-item label="外来车辆停放" prop="tempEntry">
            <el-radio-group v-model="addForm.data.tempEntry">
              <el-radio
                v-for="item in tempEntryList.data"
                :key="item.id"
                :value="item.id"
              >
                {{ item.name }}
              </el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span="13">
          <el-form-item label="免费离场时间" prop="leaveTime">
            <el-input
              v-model="addForm.data.leaveTime"
              style="width: 320px"
              placeholder="请输入免费离场时间"
            >
              <template #append>分钟</template>
            </el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="11">
          <el-form-item label="线上卡办理" prop="cardOnline">
            <el-radio-group v-model="addForm.data.cardOnline">
              <el-radio
                v-for="item in cardOnlineList.data"
                :key="item.id"
                :value="item.id"
              >
                {{ item.name }}
              </el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span="13">
          <el-form-item label="电子停车券" prop="elecCoupon">
            <el-radio-group v-model="addForm.data.elecCoupon">
              <el-radio
                v-for="item in elecCouponList.data"
                :key="item.id"
                :value="item.id"
              >
                {{ item.name }}
              </el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="11">
          <el-form-item label="车场预约" prop="reservable">
            <el-radio-group v-model="addForm.data.reservable">
              <el-radio v-for="item in reserveList.data" :key="item.id" :value="item.id">
                {{ item.name }}
              </el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span="13">
          <el-form-item label="电子发票" prop="elecInvoice">
            <el-radio-group v-model="addForm.data.elecInvoice">
              <el-radio
                v-for="item in elecInvoiceList.data"
                :key="item.id"
                :value="item.id"
              >
                {{ item.name }}
              </el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
      </el-row>
      <el-form-item>
        <div class="footer">
          <div></div>
          <div>
            <el-button class="reset-btn" @click="resetForm(addFormRef)">重 置</el-button>
            <el-button class="confirm-btn" @click="submitForm(addFormRef)"
              >确 认</el-button
            >
          </div>
        </div>
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from "vue";
import { Plus, Delete, ZoomIn } from "@element-plus/icons-vue";
import { getUpload, getAddCpark } from "../request.js";
const emits = defineEmits(["operationDone"]);

const props = defineProps({
  listData: {
    type: Object,
    default: () => {},
  },
});

const addFormRef = ref("");
const addForm = reactive({
  data: {
    infield: 1,
  },
});

const rules = reactive({
  link: [{ required: true, message: "请输入联系人", trigger: "blur" }],
  phone: [{ required: true, message: "请输入联系电话", trigger: "blur" }],
  comId: [{ required: true, message: "请选择物业名称", trigger: "change" }],
  name: [{ required: true, message: "请输入场库名称", trigger: "blur" }],
  status: [{ required: true, message: "请选择运营状态", trigger: "change" }],
  category: [{ required: true, message: "请选择车场类别", trigger: "change" }],
  type: [{ required: true, message: "请选择建筑类别", trigger: "change" }],
  totalSpaces: [{ required: true, message: "请输入泊位数", trigger: "blur" }],
  inSpaces: [{ required: true, message: "请输入套场泊位数", trigger: "blur" }],
  longitude: [{ required: true, message: "请输入经度", trigger: "blur" }],
  latitude: [{ required: true, message: "请输入纬度", trigger: "blur" }],
  address: [{ required: true, message: "请输入具体位置", trigger: "blur" }],
  fileId: [{ required: true, message: "请选择车场图片", trigger: "blur" }],
  tempEntry: [{ required: true, message: "请选择外来车辆停放", trigger: "change" }],
  leaveTime: [{ required: true, message: "请输入免费离场时间", trigger: "blur" }],
  cardOnline: [{ required: true, message: "请选择线上卡办理", trigger: "change" }],
  elecCoupon: [{ required: true, message: "请选择电子停车券", trigger: "change" }],
  reservable: [{ required: true, message: "请选择车场预约", trigger: "change" }],
  elecInvoice: [{ required: true, message: "请选择电子发票", trigger: "change" }],
});

// 图片
const fileList = ref([]);

const beforeAvatarUpload = (file) => {
  return new Promise(async (resolve, reject) => {
    if (
      file.type !== "image/jpeg" &&
      file.type !== "image/png" &&
      file.type !== "image/jpg"
    ) {
      ElMessage.error("所上传图片类型不支持");
      reject();
    } else if (file.size / 1024 > 100) {
      ElMessage.error("所上传图片不能超过100K");
      reject();
    }
  });
};

const fileIdObj = ref([]);
const imageObj = ref([]);

const fileListUpLoad = (uploadFile) => {
  console.log("uploadFile ===>", uploadFile);
  const fileSize = uploadFile.size / 1024;
  //   const file = uploadFile.raw;
  if (fileSize < 100) {
    getUpload({
      file: uploadFile.raw,
      fileType: "img",
      bucket: "cipp-cpark",
      tags: "场库新增",
    })
      .then((res) => {
        console.log(res);
        fileIdObj.value.push(res.data.result.id);
        addForm.data.fileId = fileIdObj.value.join("|");
        imageObj.value.push(res.data.result.bucket + "/" + res.data.result.filePath);
        addForm.data.image = imageObj.value.join("|");
        addFormRef.value.validateField("fileId");
      })
      .catch((error) => {
        console.error("上传失败", error);
      });
  }
};

const handleRemove = (val) => {
  const indexToRemove = fileList.value.findIndex((item) => item.uid === val.uid);
  fileList.value = fileList.value.filter((item, index) => index !== indexToRemove);
  const uid = addForm.data.fileId.split("|");
  const images = addForm.data.image.split("|");
  const img = uid.map((id, index) => {
    return {
      uid: id,
      url: images[index],
    };
  });
  const array = img.filter((item, index) => index !== indexToRemove);
  console.log(array);
  const fileId = array.map((item) => item.uid).join("|");
  const image = array.map((item) => item.url).join("|");
  addForm.data.fileId = fileId;
  addForm.data.image = image;
  console.log(addForm.data);
};

const comNameList = reactive({
  data: [],
});

const statusList = reactive({
  data: [],
});

const categoryList = reactive({
  data: [],
});

const typeList = reactive({
  data: [],
});

const infieldList = reactive({
  data: [
    {
      id: 1,
      name: "是",
    },
    {
      id: 0,
      name: "否",
    },
  ],
});

const tempEntryList = reactive({
  data: [
    {
      id: 1,
      name: "启用",
    },
    {
      id: 0,
      name: "关闭",
    },
  ],
});

const cardOnlineList = reactive({
  data: [
    {
      id: 1,
      name: "启用",
    },
    {
      id: 0,
      name: "关闭",
    },
  ],
});

const elecCouponList = reactive({
  data: [
    {
      id: 1,
      name: "启用",
    },
    {
      id: 0,
      name: "关闭",
    },
  ],
});

const reserveList = reactive({
  data: [
    {
      id: 1,
      name: "启用",
    },
    {
      id: 0,
      name: "关闭",
    },
  ],
});

const elecInvoiceList = reactive({
  data: [
    {
      id: 1,
      name: "启用",
    },
    {
      id: 0,
      name: "关闭",
    },
  ],
});

const submitForm = (formEl) => {
  if (!formEl) return;
  formEl.validate((valid) => {
    if (valid) {
      comNameList.data.forEach((item) => {
        if (addForm.data.comId == item.key) {
          addForm.data.comName = item.value;
        }
      });
      const contactInfo = {
        name: addForm.data.link,
        phone: addForm.data.phone,
      };
      addForm.data.contacts = JSON.stringify(contactInfo);
      console.log(addForm.data);
      getAddCpark(addForm.data).then((res) => {
        if (res.data.code === 0) {
          ElMessage({
            type: "success",
            message: res.data.result,
          });
          emits("operationDone");
        } else {
          ElMessage.error(res.data.msg);
        }
      });
    }
  });
};

const resetForm = async (formEl) => {
  if (!formEl) return;
  addForm.data = {
    infield: 1,
  };
  formEl.resetFields();
};

onMounted(() => {
  setTimeout(() => {
    comNameList.data = props.listData.comNameList;
    statusList.data = props.listData.statusList;
    categoryList.data = props.listData.categoryList;
    typeList.data = props.listData.typeList;
  }, 1000);
});
</script>

<style lang="less" scoped>
.footer {
  width: 100%;
  display: flex;
  justify-content: space-between;
}
.reset-btn {
  width: 65px;
  height: 32px;
  background: #ffffff;
  border-radius: 2px;
  border: 1px solid #d9d9d9;
  font-weight: 400;
  font-size: 14px;
  color: rgba(0, 0, 0, 0.65);
}
.confirm-btn {
  width: 65px;
  height: 32px;
  background: #007aff;
  border-radius: 2px;
  font-weight: 400;
  font-size: 14px;
  color: #ffffff;
}
</style>
